package com.hyh.admin.controller.resources;

import com.hyh.ad.common.core.domain.AjaxResult;
import com.hyh.ad.common.utils.SecurityUtils;
import com.hyh.admin.domain.resources.ResourcesCommunity;
import com.hyh.admin.service.ResourcesCommunityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/api/community")
@Api(tags = "资源社区上传")
public class UploadCommunityController {

    @Value("${upload.avatar}")
    private String UPLOAD_DIR;

    @Autowired
    private ResourcesCommunityService resourcesCommunityService;


    /**
     * 上传资源文件并保存资源信息
     * @param file 上传的资源文件
     * @param title 标题
     * @param content 描述
     * @return 上传结果
     */
    @PostMapping(value = "/add")
    @ApiOperation(value = "上传资源文件")
    public AjaxResult uploadFile(@RequestParam(value = "file", required = false) MultipartFile file,
                                 @RequestParam("title") String title,
                                 @RequestParam("content") String content) {

        // 获取项目路径
        String projectPath = System.getProperty("user.dir");
        Path uploadPath = Paths.get(projectPath, UPLOAD_DIR);

        // 创建上传目录
        if (!Files.exists(uploadPath)) {
            try {
                Files.createDirectories(uploadPath);
            } catch (IOException e) {
                return AjaxResult.error("创建上传目录失败：" + e.getMessage());
            }
        }

        // 处理文件上传
        try {
            String originalFilename = file.getOriginalFilename();
            String timestampedFilename = System.currentTimeMillis() + "_" + originalFilename;
            File destinationFile = new File(uploadPath.toFile(), timestampedFilename);
            file.transferTo(destinationFile);

            String fileUrl = "/" + UPLOAD_DIR + "/" + timestampedFilename;

            // 创建资源对象并保存
            ResourcesCommunity resourcesCommunity = new ResourcesCommunity();
            resourcesCommunity.setTitle(title);
            resourcesCommunity.setContent(content);
            resourcesCommunity.setFileUrl(timestampedFilename); // 只保存上传文件的路径
            resourcesCommunity.setUserId(SecurityUtils.getLoginUser().getUser().getId());
            int saveResult = resourcesCommunityService.saveResourcesCommunity(resourcesCommunity);
            if (saveResult <= 0) {
                return AjaxResult.error("资源信息保存失败");
            }

            // 返回上传的文件信息
            Map<String, String> result = new HashMap<>();
            result.put("title", title);
            result.put("content", content);
            result.put("file", fileUrl);

            return AjaxResult.success("上传成功", result);
        } catch (IOException e) {
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }
}
